package com.example.securityconfiggen.util;

import org.springframework.stereotype.Component;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 密钥生成工具类，用于生成AES-256和SHA-256密钥
 */
@Component
public class KeyGeneratorUtil {

    /**
     * 生成AES-256密钥
     *
     * @return Base64编码的AES-256密钥
     * @throws NoSuchAlgorithmException 如果AES算法不可用
     */
    public static String generateAesKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256, SecureRandom.getInstanceStrong());
        SecretKey secretKey = keyGenerator.generateKey();
        return Base64.getEncoder().encodeToString(secretKey.getEncoded());
    }

    /**
     * 生成用于HMAC SHA-256的密钥
     *
     * @param keySizeInBytes 密钥大小（字节数）
     * @return Base64编码的密钥
     */
    public static String generateHmacSha256Key(int keySizeInBytes) {
        byte[] key = new byte[keySizeInBytes];
        new SecureRandom().nextBytes(key);
        return Base64.getEncoder().encodeToString(key);
    }

    /**
     * 使用指定的种子生成SHA-256哈希
     *
     * @param seed 用于生成哈希的种子字符串
     * @return 十六进制格式的SHA-256哈希
     * @throws NoSuchAlgorithmException 如果SHA-256算法不可用
     */
    public static String generateSha256Hash(String seed) throws NoSuchAlgorithmException {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hashBytes = digest.digest(seed.getBytes());
        return bytesToHex(hashBytes);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param bytes 要转换的字节数组
     * @return 十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    /**
     * 生成所有类型的密钥
     *
     * @return 包含不同类型密钥的Map
     * @throws NoSuchAlgorithmException 如果所需算法不可用
     */
    public static Map<String, String> generateAllKeys() throws NoSuchAlgorithmException {
        Map<String, String> keys = new HashMap<>();
        
        // 生成AES-256密钥
        String aesKey = generateAesKey();
        keys.put("aesKey", aesKey);
        
        // 生成HMAC SHA-256密钥（32字节 = 256位）
        String hmacKey = generateHmacSha256Key(32);
        keys.put("hmacKey", hmacKey);
        
        // 生成一个随机种子的SHA-256哈希
        String seed = Long.toString(System.currentTimeMillis()) + Math.random();
        String sha256Hash = generateSha256Hash(seed);
        keys.put("sha256Hash", sha256Hash);
        
        return keys;
    }
} 